<template>
  <div class="todo-container">
    <div class="todo-wrap">
      <MyHeader/>
      <MyList :todos="todos"/>
      <MyFooter :todos="todos"/>
    </div>
  </div>
</template>

<script>


import MyHeader from "@/components/MyHeader/index.vue";
import MyList from "@/components/MyList/index.vue";
import MyFooter from "@/components/MyFooter/index.vue";

export default {
  name: 'App',
  components: {
    MyFooter,
    MyList,
    MyHeader
  },
  mounted() {
    this.$bus.$on('add-todo', this.addTodo)
    this.$bus.$on('check-todo', this.checkTodo)
    this.$bus.$on('delete-todo', this.deleteTodo)
    this.$bus.$on('check-all-todo', this.checkAllTodo)
    this.$bus.$on('clear-all-todo', this.clearAllTodo)
  },
  beforeDestroy() {
    // 卸载自定义事件 - 编程式
    this.$bus.$off(['add-todo'])
    this.$bus.$off(['check-todo', 'delete-todo'])
    this.$bus.$off(['check-all-todo', 'clear-all-todo'])
  },
  data() {
    return {
      // 浏览器本地存储, 默认值
      todos: JSON.parse(localStorage.getItem('todos')) || []
    }
  },
  methods: {
    addTodo(todo) {
      this.todos.unshift(todo)
    },
    checkTodo(id) {
      this.todos.map(todo => {
        if (todo.id === id) todo.done = !todo.done
        return todo
      })
    },
    deleteTodo(id) {
      this.todos = this.todos.filter(todo => todo.id !== id)
    },
    checkAllTodo(done) {
      this.todos.map(todo => {
        todo.done = done
        return todo
      })
    },
    clearAllTodo() {
      this.todos = this.todos.filter(todo => !todo.done)
    }
  },
  watch: {
    todos: {
      immediate: true,
      deep: true,
      handler(todos) {
        localStorage.setItem("todos", JSON.stringify(todos))
      }
    }
  }
}
</script>

<style lang="css">
/*base*/
body {
  background: #fff;
}

.btn {
  display: inline-block;
  padding: 4px 12px;
  margin-bottom: 0;
  font-size: 14px;
  line-height: 20px;
  text-align: center;
  vertical-align: middle;
  cursor: pointer;
  box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.2), 0 1px 2px rgba(0, 0, 0, 0.05);
  border-radius: 4px;
}

.btn-danger {
  color: #fff;
  background-color: #da4f49;
  border: 1px solid #bd362f;
}

.btn-danger:hover {
  color: #fff;
  background-color: #bd362f;
}

.btn:focus {
  outline: none;
}

.todo-container {
  width: 600px;
  margin: 0 auto;
}

.todo-container .todo-wrap {
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 5px;
}


</style>
